package com.zhoug.common.router;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;


import com.zhoug.common.utils.LogUtils;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

/**
 * 描述：页面路由器
 * zhougan
 * 2020/2/24
 **/
public class ZRouter {
    private static final String TAG = ">>>ZRouter";
    /**
     * 发现或者创建新的Fragment
     * @param fm
     * @param cls
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T extends Fragment> T findOrCreateByTag(FragmentManager fm, Class<T> cls){
        T fragmentByTag = (T) fm.findFragmentByTag(cls.getCanonicalName());
        if(fragmentByTag==null){
            try {
                fragmentByTag = cls.newInstance();
                LogUtils.d(TAG, "findOrCreateByTag: 创建新的"+cls.getName());
            } catch (IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
        }else{
            LogUtils.d(TAG, "findOrCreateByTag: 复用:"+fragmentByTag);
        }
        return fragmentByTag;
    }

    /**
     * 启动activity
     * @param context
     * @param cls
     */
    public static void navigation(Context context, Class cls){
        Intent intent=new Intent(context, cls);
        context.startActivity(intent);
    }



    /**
     * 启动activity
     * @param context
     * @param cls
     * @param bundle
     */
    public static void navigation(Context context, Class cls, Bundle bundle){
        Intent intent=new Intent(context, cls);
        if(bundle!=null){
            intent.putExtras(bundle);
        }
        context.startActivity(intent);
    }

    /**
     * startActivityForResult
     * @param activity
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public static void navigation(Activity activity, Class cls, Bundle bundle, int requestCode){
        Intent intent=new Intent(activity, cls);
        if(bundle!=null){
            intent.putExtras(bundle);
        }
        activity.startActivityForResult(intent,requestCode);
    }

    /**
     * startActivityForResult
     * @param fragment
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public static void navigation(Fragment fragment, Class cls, Bundle bundle, int requestCode){
        Intent intent=new Intent(fragment.getContext(), cls);
        if(bundle!=null){
            intent.putExtras(bundle);
        }
        fragment.startActivityForResult(intent,requestCode);
    }


}
